var mongoose = require('../../../../../framework/mongoose');
var service = require('./service');

var CmsGallery = require('./model').CmsGallery;
var CmsPicture = require('./model').CmsGalleryPicture

//Rest Interface
exports.queryGalleryBySubId = function(req, res){
    CmsGallery.find({subscription: req.query.subId}).sort('order').exec(function (err, galleries) {
        CmsPicture.find({gallery: galleries[0].id}).sort('order').exec(function (err, pictures) {
            res.send({code: 1, data: {gallery: galleries[0], pictures: pictures}});
        });
    });
};
exports.galleryById = function(req, res){
    mongoose.findById(CmsGallery, req.params.id, function(gallery) {
        res.send({code: 1, data: gallery});
    });
};

exports.saveGallery = function (req, res) {
    var gallery = new CmsGallery({
        name: req.body.name,
        descr: req.body.descr,
        createDate: new Date()
    });
    gallery.save(function(){
        return res.send({code:1});
    });
};

exports.updateGallery = function(req, res){
    CmsGallery.findByIdAndUpdate(
        req.params.id,
        {
            name: req.body.name,
            descr: req.body.descr,
            updateDate: new Date()
        }, function(){
            return res.send({code:1});
        }
    )
};
exports.deleteGallery = function(req, res){
    CmsGallery.findByIdAndRemove(req.params.id, function(){
        return res.send({code:1});
    })
};

exports.queryPictureByGalleryId = function(req, res){
    CmsPicture.find({subscription: req.query.galleryId}).sort('order').exec(function (err, pictures) {
        res.send({code: 1, data: {pictures: pictures}});
    });
};
exports.pictureById = function(req, res){
    mongoose.findById(CmsPicture, req.params.id, function(picture) {
        res.send({data: picture});
    });
};
exports.savePicture = function (req, res) {
    var cmsPicture = new CmsPicture({
        title: req.body.title,
        url: req.body.url,
        gallery: req.body.galleryId
    });

    cmsPicture.save(function(){
        return res.send({code: 1});
    });
};
exports.updatePicture = function(req, res){
    CmsPicture.findByIdAndUpdate(
        req.params.id,
        {
            title: req.body.title,
            url: req.body.url
        }, function(){
            res.send({code: 1});
        }
    )
};
exports.deletePicture = function(req, res){
    CmsPicture.findByIdAndRemove(req.params.id, function(){
        return res.send({code: 1});
    })
};